#include "librawsocket.h"

#define BUFSIZE 1000
void show_usage(int argc, char *argv[]) 
{


}

#define IFNAME "eth0"

int main (int argc, char *argv[])
{

  int s;

  int len;
   RawSocket *rsock = new RawSocket();
  if (argc != 4) {
    printf("usage: %s localdev remoteipaddr port \n", argv[0]);
    printf("eg: \n");
    printf("%s eth0 192.168.1.1 8888 \n", argv[0]);
    exit(0);
  }
  struct sockaddr_in my_addr;
  struct sockaddr_in remote_addr;
  struct ifreq interface;
  strncpy(interface.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ);
  char buf[BUFSIZE];
    
    
  memset (&remote_addr, 0, sizeof (remote_addr));
  remote_addr.sin_family = AF_INET;
  remote_addr.sin_addr.s_addr = inet_addr (argv[2]);
  remote_addr.sin_port = htons (strtol(argv[3],NULL,10));

 /* memset (&my_addr, 0, sizeof (my_addr));
  my_addr.sin_family = AF_INET;
  my_addr.sin_addr.s_addr = inet_addr (argv[1]);
  my_addr.sin_port = htons (strtol(argv[3], NULL, 10));
    */
  if ((s = rsock->socket (PF_INET, SOCK_STREAM, 0)) < 0) {
      perror ("socket error");
      return 1;
  }
if (rsock->setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, \
  (char *)&interface, sizeof(interface))  < 0) {
       perror("SO_BINDTODEVICE failed");
      /* Deal with error... */
} 
 /* if (bind (s, (struct sockaddr *) &my_addr, sizeof (struct sockaddr)) < 0)
  {

      perror ("bind");

      return 1;

  }*/
  if (rsock->connect (s, (struct sockaddr *) &remote_addr, sizeof (struct sockaddr)) < 0) {
      perror ("connect error");
      return 1;

    }

  printf ("connected to server\n");
/*
  len = recv (s, buf, BUFSIZE, 0);

  buf[len] = '\0';

  printf ("%s", buf);
*/
  while (1)

    {

      printf ("Enter string to send:");

      scanf ("%s", buf);

      if (!strcmp (buf, "quit"))
            {
            
             break;
            
            }

      len = rsock->send (s, buf, strlen (buf), 0);

      len = rsock->recv (s, buf, BUFSIZE, 0);

      buf[len] = '\0';

      printf ("received:%s\n", buf);

    }

  rsock->close (s);
  delete rsock;
  return 0;

}
